package com.asia5b.a5mall.shop.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.fragment.GoodsCouponDF
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.event.CartDataChange
import com.asia5b.a5mall.middleware.event.CreateOrderEvent
import com.asia5b.a5mall.middleware.event.LoginEvent
import com.asia5b.a5mall.middleware.event.LogoutEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.cart.ShopCartFragmentVM
import com.asia5b.a5mall.middleware.model.cart.CartAllModel
import com.asia5b.a5mall.middleware.model.bean.CartHolderBean
import com.asia5b.a5mall.middleware.model.bean.CartMultiItemEntity
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.model.shop.AbsShopModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import com.asia5b.a5mall.shop.R
import com.asia5b.a5mall.shop.activity.CartActivity
import com.asia5b.a5mall.shop.adapter.ShopCartAdapter
import com.asia5b.a5mall.shop.databinding.FragmentShopcarBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.fragment_shopcar.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/1/4.
 */
@Route(path = ActCons.CartFragment)
class ShopCartFragment : SimpleFragment<ShopCartFragmentVM, FragmentShopcarBinding>() {

    override val viewModelClazz: Class<ShopCartFragmentVM>
        get() = ShopCartFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentShopcarBinding {
        return FragmentShopcarBinding.inflate(layoutInflater, container, false)
    }

    private val mDatas = arrayListOf<CartMultiItemEntity>()
    private lateinit var mAdapter: ShopCartAdapter
    private var cartAllModel: CartAllModel? = null

    override fun initView() {
        mSmartRefreshLayout = mDataBinding.autoShopcar
        mDataBinding.autoShopcar.setEnableLoadMore(false)
        if (getActivity() is CartActivity) {
            mDataBinding.headShopcar.setBackIconGone(false)
            mDataBinding.headShopcar.setStatusGone(true)
        } else {
            mDataBinding.headShopcar.setBackIconGone(true)
            mDataBinding.headShopcar.setStatusGone(false)
        }

        mAdapter = ShopCartAdapter(mDatas)
        mDataBinding.rvShopcar.run {
            layoutManager = LinearLayoutManager(requireContext())!!
            adapter = mAdapter
        }
        notifyView()

        bt_shopcar_submit.isSelected = true
        setEditStateView()
    }

    /**
     * 设置编辑状态 bt_shopcar_submit.isSelected true/false 普通/删除
     */
    fun setEditStateView() {
        bt_shopcar_submit.text = if (bt_shopcar_submit.isSelected) getString(R.string.去结算) else getString(R.string.删除)
        head_shopcar.setRithtText(if (bt_shopcar_submit.isSelected) R.string.编辑 else R.string.完成)
        ll_shopcar_price_vessel.visibility = if (bt_shopcar_submit.isSelected) View.VISIBLE else View.INVISIBLE
        mDataBinding.isShowDelete = !bt_shopcar_submit.isSelected
        mAdapter.isShowDelete = !bt_shopcar_submit.isSelected
        notifyDeleteView()
    }

    fun notifyView() {
        if (mDatas.size == 0) {
            if (UserRepository.isLogin()) {
                val buyView = View.inflate(requireContext(), R.layout.empty_item, null)
                buyView.findViewById<Button>(R.id.bt_cart_buy).setOnClickListener {
                    push(ActCons.SearchGoodsActivity)
                }
                mAdapter.setEmptyView(buyView)
            } else {
                val loginView = View.inflate(requireContext(), R.layout.item_cart_login, null)
                val textView = loginView.findViewById<Button>(R.id.bt_cart_login)
                textView.setText("${getString(R.string.登录)}/${getString(R.string.注册)}")
                loginView.findViewById<Button>(R.id.bt_cart_login).setOnClickListener {
                    push(ActCons.LoginActivity)
                }
                mAdapter.setEmptyView(loginView)
            }

        }
        var checkNum = 0
        var goodsNum = 0
        for (item in mDatas) {
            if (item is AbsGoodsModel) {
                if (item.absGoodsIsChecked) {
                    checkNum++
                }
                goodsNum++
            }

        }
        cb_shopcar_check.isChecked = ((checkNum == goodsNum) && (checkNum != 0))

//        //代付款
//        val total_price = cartAllModel?.total_price?.total_price
//                ?: 0.0
//        //总价
//        val orgPrice = cartAllModel?.total_price?.original_price
//                ?: 0.0
//        //优惠价
//        val cashPrice = cartAllModel?.total_price?.cash_back
//                ?: 0.0
        tv_shopcar_totalprice.setText("0.00")
        tv_shopcar_subprice.setText("0.00")
        cartAllModel?.total_price?.run {
            //总计
            CurrencyPriceBuilder3().run {
                textView = tv_shopcar_totalprice
                price = total_price
                priceList = total_price_list
                build()
            }
            //优惠
            CurrencyPriceBuilder3().run {
                textView = tv_shopcar_subprice
                price = cash_back
                priceList = cash_back_list
                build()
            }
        }

        mAdapter.notifyDataSetChanged()
    }

    /**
     * 更新删除相关视图
     */
    fun notifyDeleteView() {


        //设置店铺全选按钮
        val iterator = mDatas.iterator()
        //上一个店铺
        var preCartShopModel: AbsShopModel? = null
        var allCheckShop = true
        while (iterator.hasNext()) {
            val next = iterator.next()
            if (next is AbsShopModel) {
                //先设置上一个店铺
                preCartShopModel?.checkedDeleteObservable?.set(allCheckShop)
                //赋值下一个店铺
                preCartShopModel = next
                allCheckShop = true
            }
            if (next is AbsGoodsModel) {
                if (allCheckShop) {
                    allCheckShop = next.checkedDeleteObservable.get()
                }
            }
        }
        //先设置上一个店铺
        preCartShopModel?.checkedDeleteObservable?.set(allCheckShop)

        //设置全选按钮
        var allCheck = true
        for (item in mDatas) {
            if (item is AbsShopModel) {
                if (allCheck) {
                    allCheck = item.checkedDeleteObservable.get()
                }
            }
            if (item is AbsGoodsModel) {
                if (allCheck) {
                    allCheck = item.checkedDeleteObservable.get()
                }
            }

        }
        cb_shopcar_check_delete.isChecked = allCheck

    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mViewModel.loadCartData(1)
    }

    override fun initEvent() {
        //全选删除
        ll_shopcar_check_delete.setOnClickListener {
            cb_shopcar_check_delete.performClick()
        }
        //全选删除
        cb_shopcar_check_delete.setOnClickListener {
            for (data in mDatas) {
                if (data is AbsShopModel) {
                    data.checkedDeleteObservable.set(cb_shopcar_check_delete.isChecked)
                }
                if (data is AbsGoodsModel) {
                    data.checkedDeleteObservable.set(cb_shopcar_check_delete.isChecked)
                }
            }
//            mAdapter.notifyDataSetChanged()
        }
        //全选
        ll_shopcar_check.setOnClickListener {
            cb_shopcar_check.performClick()
        }
        //全选
        cb_shopcar_check.setOnClickListener {
            if (!UserRepository.isLogin(requireContext())) {
                return@setOnClickListener
            }
            mViewModel.allCheck(cb_shopcar_check.isChecked)
        }

        //去结算
        bt_shopcar_submit.setOnClickListener {
            if (!UserRepository.isLogin(requireContext())) {
                return@setOnClickListener
            }
            if (bt_shopcar_submit.isSelected) {//去结算
                var checkNum = 0
                for (item in mDatas) {
                    if (item is AbsGoodsModel) {
                        if (item.absGoodsIsChecked) {
                            checkNum++
                        }
                    }

                }
                if (checkNum == 0) {
                    showMessage(R.string.尚未选择商品)
                } else {
                    push(ActCons.OrderPlaceActivity)
                }
            } else {//删除
                val selectDatas = arrayListOf<String>()
                for (itemEntity in mDatas) {
                    if (itemEntity is AbsGoodsModel) {
                        if (itemEntity.checkedDeleteObservable.get()) {
                            selectDatas.add("${itemEntity.absGoodsSkuId}")
                        }
                    }
                }
                if (selectDatas.size == 0) {
                    showMessage(R.string.尚未选择商品)
                } else {
                    CancelSureViewModel(requireContext(), R.string.是否需要删除选中商品) {
                        val join = TextUtils.join(",", selectDatas)
                        deleteGoods(join)
                    }.show()

                }
            }
        }


        //编辑
        head_shopcar.setRightClickListener {
            if (mDatas.size == 0) {
                showMessage(R.string.购物车暂无商品)
                return@setRightClickListener
            }
            bt_shopcar_submit.isSelected = !bt_shopcar_submit.isSelected
            setEditStateView()
            mAdapter.notifyDataSetChanged()
        }

        mAdapter.setOnItemChildClickListener{ adapter, view, position ->
            val cartMultiItemEntity = mAdapter.getItem(position)!!
            when (view.id) {
                R.id.cb_shopcar_shop_check -> {//店铺选中
                    val shopItemViewModel = cartMultiItemEntity as AbsShopModel
                    shopCheck(shopItemViewModel.absShopId, !shopItemViewModel.isCheck)
                }
                R.id.cb_shopcar_shop_check_delete -> {//店铺选中删除
                    val shopItemViewModel = cartMultiItemEntity as AbsShopModel
                    for (itemEntity in mDatas) {
                        if (itemEntity is AbsGoodsModel) {
                            if (itemEntity.absGoodsShopId == shopItemViewModel.absShopId) {
                                itemEntity.checkedDeleteObservable.set((view as CheckBox).isChecked)
                            }
                        }
                    }
                    notifyDeleteView()
                }
                R.id.tv_shopcar_coupon -> { //查看优惠券
                    val shopItemViewModel = cartMultiItemEntity as AbsShopModel
                    mViewModel.getCouponList(shopItemViewModel.absShopId)
                }
                R.id.tv_plusview_add -> {        //增加
                    val cartGoodsItemViewModel = cartMultiItemEntity as AbsGoodsModel
                    goodsEdit(cartGoodsItemViewModel.absGoodsSkuId, cartGoodsItemViewModel.absGoodsSetNum + 1, null)
                }
                R.id.tv_plusview_sub -> {        //减
                    val cartGoodsItemViewModel = cartMultiItemEntity as AbsGoodsModel
                    val numI = cartGoodsItemViewModel.absGoodsSetNum - 1
                    if (numI <= 0) {
//                        showMessage(String.format(ResString.get(R.string.shopcar_minqty_notice), 1))
                        return@setOnItemChildClickListener
                    }
                    goodsEdit(cartGoodsItemViewModel.absGoodsSkuId, cartGoodsItemViewModel.absGoodsSetNum - 1, null)
                }
                R.id.cb_shopcar_goods_check -> {        //复选框
                    val cartGoodsItemViewModel = cartMultiItemEntity as AbsGoodsModel
                    goodsEdit(cartGoodsItemViewModel.absGoodsSkuId, null, !cartGoodsItemViewModel.absGoodsIsChecked)
                }
                R.id.cb_shopcar_goods_check_delete -> {        //复选框
                    notifyDeleteView()
                }
                R.id.tv_shopcar_collect -> {        //关注
                    val cartGoodsItemViewModel = cartMultiItemEntity as AbsGoodsModel
                    mViewModel.collectGoods(cartGoodsItemViewModel.absGoodsId)
                }
                R.id.tv_shopcar_delete -> {        //删除
                    val cartGoodsItemViewModel = cartMultiItemEntity as AbsGoodsModel
                    CancelSureViewModel(requireContext(), R.string.是否需要删除选中商品) {
                        deleteGoods(cartGoodsItemViewModel.absGoodsSkuId)
                    }.show()
                }

            }
        }


    }


    override fun lazyFetchData() {
        mViewModel.loadCartData(0)
    }

    override fun startObserver() {
        mViewModel.getCouponListLiveData.observe(this, Observer { list ->
            if (list.isNullOrEmpty()) {
                showMessage(getString(R.string.暂无优惠券))
            } else {
                val goodsCouponDF = GoodsCouponDF().then {
                    it.mDatas.addAll(list!!)
                    it.type = 1
                }
                goodsCouponDF.show(childFragmentManager, "GoodsCouponDF")
            }
        })
        mViewModel.loadCartDataLiveData.observe(this, Observer { cartAllModel ->
            this.cartAllModel = cartAllModel
            bt_shopcar_submit.isSelected = true
            setEditStateView()

            mDatas.clear()
            cartAllModel?.cart_list?.forEach { cartShopItemViewModel ->

                mDatas.add(cartShopItemViewModel)

                cartShopItemViewModel?.absShopGoodsList?.forEach { cartGoodsItemViewModel ->
                    mDatas.add(cartGoodsItemViewModel)
                }
                mDatas.add(CartHolderBean())
            }
            notifyView()
        })
    }


    /**
     * @Note   列表店铺Item选中回调
     * @param  shopId 店铺ID
     * @param  checked 是否选中
     */
    fun shopCheck(shopId: Int, checked: Boolean) {
        mViewModel.shopCheck(shopId, checked)
    }

    /**
     * @Note   商品选中回调
     * @param  productId 商品ProductId
     * @param  checked 是否选中
     */
    fun goodsEdit(productId: Int, num: Int?, checked: Boolean?) {
        mViewModel.editItem(productId, checked, num)
    }

    fun deleteGoods(productId: Int) {
        deleteGoods("${productId}")
    }

    fun deleteGoods(productIds: String) {
        mViewModel.deleteGoods(productIds)
    }


    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCartDataChange(event: CartDataChange) {
        mViewModel.loadCartData(1)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogoutEvent(event: LogoutEvent) {
        mDatas.clear()
        notifyView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCreateOrderEvent(event: CreateOrderEvent) {
        mViewModel.loadCartData(1)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginEvent(event: LoginEvent) {
        mViewModel.loadCartData(1)
    }

}